const WebSocket = require("ws");

const WS_URL = process.env.WS || "ws://localhost:3000/user-service/websocket";
const SELECT_ROLE_ID = Number(process.env.ROLE_ID || 2001); // 可通过环境变量传入

function send(ws, obj) {
  ws.send(JSON.stringify(obj));
}

function main() {
  const ws = new WebSocket(WS_URL);
  let got1480 = false;

  ws.on("open", () => {
    console.log("WS connected:", WS_URL);
    // 选角（如果网关需要）
    send(ws, { c: 5, characterId: SELECT_ROLE_ID });
    setTimeout(() => send(ws, { c: 1480 }), 200);

    // 超时退出
    setTimeout(() => {
      if (!got1480) {
        console.error("Timeout: no 1480 response");
        ws.close();
        process.exit(1);
      }
    }, 2000);
  });

  ws.on("message", (raw) => {
    let msg;
    try {
      msg = JSON.parse(raw.toString());
    } catch (e) {
      console.error("parse error", e);
      return;
    }
    if (msg && msg.act_id === 1480) {
      console.log("1480 RESPONSE:", JSON.stringify(msg));
      got1480 = true;
      ws.close();
    } else {
      // 其他消息打印但不退出
      // console.log("RECV:", msg);
    }
  });

  ws.on("error", (e) => console.error("WS error", e));
  ws.on("close", () => console.log("WS closed"));
}

main();


